package com.situ.stl.fore;

import com.situ.stl.entity.Member;
import com.situ.stl.entity.Result;
import com.situ.stl.service.MemberService;
import com.situ.stl.util.JWTUtil;
import com.situ.stl.vo.MemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/** 
 * Controller层 - 会员
 */
@RestController("foreMemberController")
@RequestMapping( value = "/fore/member")
public class MemberController {

    /** 
     */
    @Autowired 
    private MemberService memberService;

    /**
     * add
     */
    @PostMapping("/reg")
    public Result reg(@RequestBody Member member) {
        try {
            memberService.add(member);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * login
     */
    @PostMapping("/login")
    public Result login(@RequestBody MemberVo member) {
        try {
            Member loginMember = memberService.login(member);
            String token = JWTUtil.createJWT(loginMember.getPhone());
            return Result.success(token, loginMember);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * reset password
     */
    @PostMapping("/resetPwd")
    public Result resetPwd(@RequestBody MemberVo member) {
        try {
            if (member.getNewPassword().equals(member.getOldPassword())){
                throw new Exception("新旧密码不能一样！");
            }
            if ( ! member.getNewPassword().equals(member.getRepeatPassword())){
                throw new Exception("两次密码不一致！");
            }
            memberService.resetPwd(member);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * edit
     */
    @PutMapping
    public Result edit( @RequestBody Member member) {
        try {
            memberService.edit(member);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }


}